<?php
declare (strict_types=1);

namespace app\platform\validate;

use think\Validate;

class Merchant extends Validate
{
    protected $rule = [
        'username'         => 'require|checkExistUsername',
        'cellphone'        => 'require|regex:^1[3-9]\d{9}$|checkExistCellphone',
        'email'            => 'require|email|checkExistEmail',
        'password'         => 'require',
        'confirm_password' => 'require|checkConfirmPassword',
    ];

    protected $message = [
        'username.require'  => '请输入用户名',
        'cellphone.require' => '请输入手机号',
        'cellphone.regex'   => '请输入正确手机号格式',
        'email.require'     => '请输入邮箱',
        'email.email'       => '请输入正确的邮箱格式',
        'password'          => '请输入密码',
    ];

    protected $scene = [
        'login' => ['username', 'password'],
        'add'   => ['username', 'cellphone', 'email', 'status', 'password', 'confirm_password'],
        'edit'  => ['username', 'cellphone', 'email', 'status'],
        'pwd'   => ['password', 'confirm_password'],
    ];

    public function checkConfirmPassword($value, $rule, $data = [])
    {
        if ($value != $data['password']) {
            return '两次密码不一致';
        }

        return true;
    }

    public function checkExistUsername($value, $rule, $data = [])
    {
        $merchantModel = new \app\common\model\Merchant();
        $merchant      = $merchantModel->findUser(['username' => $value]);
        if (!empty($merchant)) {
            $row = $merchant->toArray();
            if (isset($data['id'])) {
                if ($row['id'] != $data['id']) {
                    return '用户名已存在';
                }

                return true;
            }

            return '用户名已存在';
        }

        return true;
    }

    public function checkExistCellphone($value, $rule, $data = [])
    {
        $merchantModel = new \app\common\model\Merchant();
        $merchant      = $merchantModel->findUser(['cellphone' => $value]);
        if (!empty($merchant)) {
            $row = $merchant->toArray();
            if (isset($data['id'])) {
                if ($row['id'] != $data['id']) {
                    return '手机号已存在';
                }

                return true;
            }

            return '手机号已存在';
        }

        return true;
    }

    public function checkExistEmail($value, $rule, $data = [])
    {
        $merchantModel = new \app\common\model\Merchant();
        $merchant      = $merchantModel->findUser(['email' => $value]);
        if (!empty($merchant)) {
            $row = $merchant->toArray();
            if (isset($data['id'])) {
                if ($row['id'] != $data['id']) {
                    return '邮箱已存在';
                }

                return true;
            }
            return '邮箱已存在';
        }

        return true;
    }
}
